<?php
/**
 * File Name...: application\controllers\serch.php
 * Framework...: Blackbird Framework
 * Author......: KnKill, 2010 (c) KnKill Corporation
 */



/**
 * @package Blackbird Framework
 * @subpackage Application Controllers
 * @since 0.1
 */
class Controller_Search extends Base_Controller
{



function __construct()
{
    parent::preload(); 
}



function index()
{
    $this->view->assign('title', 'Поиск');
    $this->view->display('search/main_form.php');
}



function _get_fields($array)
{
    $allowed_fields = array('artists', 'date', 'label', 'tracklist', 'catalog', 'release');
    $fields_as_string = '';
    foreach ($array as $field => $unused) {
        if (in_array($field, $allowed_fields)) {
            $fields_as_string .= '`' . $field . '`, ';
        }
    }
    return substr($fields_as_string, 0, -2);
}



function _get_limit($limit, $min = 5, $max = 30, $default = null)
{
    $limit = (int)$limit;
    if ($default == null) {
        $default = $min;
    }
    if ($limit < $min || $limit > $max) {
        $limit = $default;
    }
    return $limit;
}



function _do_search($query_string, $fields, $limit)
{
    $this->db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );
    $sql = 'SELECT * FROM `releases` WHERE MATCH (' . $this->_get_fields($fields) . ') AGAINST (:query IN BOOLEAN MODE) LIMIT :limit';
    $query = $this->db->prepare($sql);
    $query->bindParam(':query', $query_string, PDO::PARAM_STR);
    $query->bindParam(':limit', $this->_get_limit($limit), PDO::PARAM_INT);
    $query->execute();
    return $query->fetchAll();
}



function ajax_show_result()
{
    $results = $this->_do_search(input::post('query'), input::post('fields'), input::post('limit'));
    for ($i = 0; $i < count($results); $i++) {
        $results[$i]['artists'] = str_replace('|||', ', ', $results[$i]['artists']);
    }
    $this->view->assign('results', $results);
    $this->view->display('ajax_blocks/search_results.php');
}

}